import { shallowRef } from 'vue'
import { isExternal } from '@/utils/validate'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('/src/views/**/*.{vue,jsx}')

export const getRawRoute = (route) => {
  if (!route) return route
  const { matched, ...opt } = route
  return {
    ...opt,
    matched: (matched
      ? matched.map((item) => ({
        meta: item.meta,
        name: item.name,
        path: item.path
      }))
      : undefined)
  }
}

// 后端控制路由生成
export const generateRoutesFn = (routes) => {
  const res = []
  for (const route of routes) {
    const data = {
      path: route.path,
      name: route.name,
      redirect: route.redirect,
      meta: route.meta
    }
    if (route.component) {
      const component = route.component
      // 动态加载路由文件，可根据实际情况进行自定义逻辑
      if (component.includes('Layout')) {
        data.component = shallowRef(Layout)
      } else if (component.includes('ParentView')) {
        data.component = shallowRef(ParentView)
      } else {
        data.component = loadRouteView(component)
      }
    }
    // recursive child routes
    if (route.children) {
      data.children = generateRoutesFn(route.children)
    }
    res.push(data)
  }
  return res
}

// 动态加载组件
export function loadRouteView(component) {
  try {
    const key = Object.keys(modules).find((key) => {
      return key.includes(`${component}.vue`)
    })
    if (key) {
      return modules[key]
    }
    throw Error(`找不到组件${component}，请确保组件路径正确`)
  } catch (error) {
    console.error(error)
    return new Error(error)
  }
}

export const resolvePath = (parentPath, routePath = '') => {
  if (isExternal(routePath)) {
    return routePath
  }
  if (isExternal(parentPath)) {
    return parentPath
  }
  const childPath = routePath.startsWith('/') || !routePath ? routePath : `/${routePath}`
  return `${parentPath}${childPath}`.replace(/\/\//g, '/')
}
